<?php

/***  DOCUMENTATION LAYER

	Greqo Google Data Services Library

	Last Update: Nov 2006
	Author: Tom Atwell (klenwell@gmail.com)

	FUNCTIONS
		greqo_load_gdata_classes()
		greqo_request_clientlogin_token($username, $password, $service, $force=0)
		greqo_get_clientlogin_token()
		greqo_parse_gauth_response($body='', $show_google_error=1)

  NOTES
		Google authorization keys are saved to the following SESSION variable:
		
			$_SESSION['GDATA']['auth_token']

______________________________________________________________________________*/


// pear_load_gdata_classes
/*____________________________________________________________________________*/
function greqo_load_gdata_classes() 
{
// *** DATA

	// static (singleton pattern)
	$is_loaded = 0;

	// Return (void)


// *** MANIPULATE

	// load only once
	if ( $is_loaded ) return;
	
	// load classes
	require_once( GREQO_ROOT . 'PEAR/_driver.inc.php' );
	require_once( 'PEAR.php' );
	require_once( 'HTTP/Request.php' );
	$is_loaded = 1;

// *** RETURN

	return;

} // end Fx
/*____________________________________________________________________________*/



// greqo_request_token
/*____________________________________________________________________________*/
function greqo_request_clientlogin_token($username, $password, $service, $force=0) 
{
// *** DATA

	// Globals
	global $GREQO;

	// client settings
	$request_url = $GREQO['clientlogin_url'];
	$client_id = $GREQO['client_id'];

	// Internal
	$_FLAG['err'] = 0;
	$GDATA = array();
	$_code_class = 0;

	// Return
	$GDATA['token'] = 0;


// *** MANIPULATE

	// Collect body parameters
	$_BODY['Email'] = $username;
	$_BODY['Passwd'] = $password;
	$_BODY['service'] = $service;
	$_BODY['source'] = $client_id;
	
	// Sanity Checks
	foreach ( $_BODY as $_key => $_val )
	{
		if ( empty($_val) )
		{
			trigger_error("$_key empty -> request aborted", E_USER_WARNING);
			$_FLAG['err'] = 1;
		}
	}
	if ( $_FLAG['err'] ) return 0;

	// Prime Session value
	$_SESSION['GDATA']['auth_token'] = ( !empty($_SESSION['GDATA']['auth_token']) ) ? $_SESSION['GDATA']['auth_token'] : 0;

	// Do we have a token already?
	if ( !empty($_SESSION['GDATA']['auth_token']) && !$force ) return $_SESSION['GDATA']['auth_token'];

	// Call PEAR Classes
	greqo_load_gdata_classes();
	
	// PEAR Http Config
	$_CONFIG = array( 'timeout' => 10 );	
		
	// Create PEAR Client
	$GDATA_CLIENT = new HTTP_Request($request_url, $_CONFIG);
	$GDATA_CLIENT->setMethod(HTTP_REQUEST_METHOD_POST);
	
	// Build Request
	$GDATA_CLIENT->addHeader('Content-type', 'application/x-www-form-urlencoded');
	$GDATA_CLIENT->addPostData('accountType', 'HOSTED_OR_GOOGLE');
	$GDATA_CLIENT->addPostData('Email', $_BODY['Email']);
	$GDATA_CLIENT->addPostData('Passwd', $_BODY['Passwd']);
	$GDATA_CLIENT->addPostData('service', $_BODY['service']);
	$GDATA_CLIENT->addPostData('source', $_BODY['source']);
	
	// Send Request
	$GResult = $GDATA_CLIENT->sendRequest();
	
	// Check for Errors
	if ( PEAR::isError($GResult) )
	{
		$_err = $GResult->getMessage();
		trigger_error("request failed: {$_err}", E_USER_WARNING);			
		$_res_dump = print_r($GResult, 1);
		$_req_dump = print_r($GDATA_CLIENT, 1);
		#echo "Request Object Dump<pre>$_req_dump</pre>";
		#echo "Result Object Dump<pre>$_res_dump</pre>";		
		return 0;
	}
	
	// Get Code and Body
	$_code = $GDATA_CLIENT->getResponseCode();
	$_code_class = floor($_code / 100);
	$_response = $GDATA_CLIENT->getResponseBody();
	
	// Process Results
	if ( $_code_class == 2 )
	{
		$GDATA = greqo_parse_gauth_response($_response, 0);
	}
	elseif ( $_code_class == 4 )
	{
		$GDATA = greqo_parse_gauth_response($_response, 1);
		$_e = print_r($GDATA,1);
		trigger_error($_e, E_USER_WARNING);
		return 0;
	}
	else
	{
		$_response = htmlspecialchars($_response);
		trigger_error("unexpected response (code $_code): $_response", E_USER_WARNING);
		return 0;
	}
	
	// Save token to session
	if ( !empty($GDATA['token']) ) $_SESSION['GDATA']['auth_token'] = $GDATA['token'];
	

// *** RETURN

	return $GDATA['token'];

} // end Fx
/*____________________________________________________________________________*/



// greqo_get_clientlogin_token
// after it's been request (see above)
/*____________________________________________________________________________*/
function greqo_get_clientlogin_token() 
{
// *** DATA

	// Return
	$_SESSION['GDATA']['auth_token'] = ( !empty($_SESSION['GDATA']['auth_token']) ) ? $_SESSION['GDATA']['auth_token'] : 0;


// *** MANIPULATE

	if ( empty($_SESSION['GDATA']['auth_token']) )
	{
		trigger_error('no Google session token found - get token first', E_USER_WARNING);
		return 0;		
	}

// *** RETURN

	return $_SESSION['GDATA']['auth_token'];

} // end Fx
/*____________________________________________________________________________*/



// greqo_request_token
/*____________________________________________________________________________*/
function greqo_parse_gauth_response($body='', $show_google_error=1) 
{
// *** DATA

	// Hard Parameters
	$gdata_token_key = 'Auth';
	
	// Return
	$GDATA = array();
	

// *** MANIPULATE

	// Sanity Check
	if ( empty($body) )
	{
		trigger_error('empty response from Google', E_USER_WARNING);
		return 0;
	}
	
	// Parse Response
	$_LINE = explode("\n", $body);
	foreach ( $_LINE as $_string )
	{
		$_string = trim($_string);
		if ( !strpos($_string, '=') ) continue;
		
		$_PARAM = explode('=', $_string);
		$GDATA[$_PARAM[0]] = $_PARAM[1];
	}
	
	// Exception check
	if ( empty($GDATA) )
	{
		trigger_error('no GData values found', E_USER_WARNING);
		return 0;
	}
	elseif ( !empty($GDATA['Error']) && $show_google_error )
	{
		trigger_error("Google Error Response: {$GDATA['Error']}", E_USER_NOTICE);
	}
	
	// Set Auth as Token
	if ( $_PARAM[0] == $gdata_token_key ) $GDATA['token'] = $_PARAM[1];

	
// *** RETURN

	return $GDATA;
	
} // end Fx
/*____________________________________________________________________________*/

?>
